package controllers

import (
	m "models"
	//"github.com/astaxie/beego"
)

type XuserController struct {
	CommonController
}

func (this *XuserController) List() {
	page, _ := this.GetInt64("page")
	page_size, _ := this.GetInt64("rows")
	sort := this.GetString("sort")
	order := this.GetString("order")
	if len(order) > 0 {
		if order == "desc" {
			sort = "-" + sort
		}
	} else {
		sort = "T_id"
	}
	users, count := m.Getuserlist(page, page_size, sort)
	if this.IsAjax() {
		this.Data["json"] = &map[string]interface{}{"code": 0, "msg": "", "count": count, "data": &users}
		this.ServeJSON()
		return
	} else {
		//this.Data["users"] = &users
		this.TplName = this.GetTemplatetype() + "/xuserlist.html"
	}
}

func (this *XuserController) AddUser() {
	u := m.Xuser{}
	if err := this.ParseForm(&u); err != nil {
		//handle error
		this.Rsp(false, err.Error())
		return
	}
	id, err := m.AddUser(&u)
	if err == nil && id > 0 {
		this.Rsp(true, "Success")
		return
	} else {
		this.Rsp(false, err.Error())
		return
	}

}

func (this *XuserController) UpdateUser() {
	if this.Ctx.Request.Method == "POST" {
		u := m.Xuser{}
		if err := this.ParseForm(&u); err != nil {
			//handle error
			this.Rsp(false, err.Error())
			return
		}

		//更新用户信息
		id, err := m.UpdateUser(&u)
		if err == nil && id > 0 {
			this.Rsp(true, "Success")
			return
		} else {
			this.Rsp(false, "UpdateFail")
			return
		}
	} else {
		if this.IsAjax() {
			Id, _ := this.GetInt64("T_id")
			user := m.GetUserById(Id)
			this.Data["json"] = &map[string]interface{}{"data": &user}
			this.ServeJSON()
		} else {
			this.TplName = this.GetTemplatetype() + "/xuseredit.html"
		}
	}
}

func (this *XuserController) DelUser() {
	Id, _ := this.GetInt64("T_id")
	status, err := m.DelUserById(Id)
	if err == nil && status > 0 {
		this.Rsp(true, "Success")
		return
	} else {
		this.Rsp(false, err.Error())
		return
	}
}
